package com.scpii.api.common.json.serializer;

import java.io.IOException;
import java.util.regex.Matcher;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;

import com.scpii.api.common.Constants;
import com.scpii.api.domain.common.Field;
import com.scpii.api.domain.common.Field.FieldMetaType;

public class FieldSerializer extends JsonSerializer<Field> {

	@Override
	public void serialize(Field value, JsonGenerator jgen,
			SerializerProvider provider) throws IOException,
			JsonProcessingException {
		jgen.writeStartObject();
		if (value.getId() != null) {
			jgen.writeNumberField("id", value.getId());
		}
		if (value.getName() != null) {
			jgen.writeStringField("name", value.getName());
		}
		if (value.getAliasName() != null) {
			jgen.writeStringField("aliasName", value.getAliasName());
		}
		if (value.getMask() != null) {
			jgen.writeObjectField("mask", value.getMask());
		}
		if (value.getMetaType() != null) {
			jgen.writeStringField("metaType", value.getMetaType());
		}
		if (value.getValues() != null && value.getValues().length > 0) {
			jgen.writeArrayFieldStart("values");
			String[] values = value.getValues();
			for (String valueStr : values) {
				Matcher matcher = ResourceUrlSerializer.URL_REG_PATTERN
						.matcher(valueStr);
				if (!FieldMetaType.IMAGE.getValue().equals(value.getMetaType())) {
					jgen.writeString(valueStr);
					continue;
				}
				if (matcher.matches()) {
					jgen.writeString(valueStr);
				} else {
					valueStr = StringUtils.startsWith(valueStr, "/") ? valueStr
							: "/" + valueStr;
					jgen.writeString(Constants.RESOURCE_ROOT_URL + valueStr);
				}
			}
			jgen.writeEndArray();
		}
		jgen.writeEndObject();
	}
}
